//
//  ReloadDataViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/6/27.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "ReloadDataViewController.h"
#import "MainViewController.h"
@interface ReloadDataViewController ()
@property (nonatomic,copy) NSString * AllStr;
@property (nonatomic,strong)NSMutableDictionary *allDataDictionary;
@end

@implementation ReloadDataViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(26, 167, 157);
    [self creatBtn];
}

-(void)creatBtn{
    self.pleaseReloadLabel = [[UILabel alloc]init];
    self.pleaseReloadLabel.text = @"请先同步数据";
    [self.pleaseReloadLabel setTextAlignment:NSTextAlignmentCenter];
    self.pleaseReloadLabel.textColor = [UIColor whiteColor];
    self.pleaseReloadLabel.font = [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal];
    [self.view addSubview:self.pleaseReloadLabel];
    [self.pleaseReloadLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).with.offset(180*AutoScaleVertical);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(400*AutoScaleHorizontal, 80*AutoScaleVertical));
    }];
    
    self.ReloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ReloadBtn.backgroundColor = UIColorFromRGB(223, 242, 241);
    [self.ReloadBtn setTitle:@"同步数据" forState:UIControlStateNormal];
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"]==nil) {
        [self.ReloadBtn addTarget:self action:@selector(reloadAllData) forControlEvents:UIControlEventTouchUpInside];
    }else{
    
    [self.ReloadBtn addTarget:self action:@selector(uploadData) forControlEvents:UIControlEventTouchUpInside];
    }
    self.ReloadBtn.titleLabel.font = [UIFont boldSystemFontOfSize:22*AutoScaleHorizontal];
    [self.ReloadBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.ReloadBtn];
    [self.ReloadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(150*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 80*AutoScaleVertical));
    }];
    
    self.enterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.enterBtn.backgroundColor = UIColorFromRGB(211, 94, 61);
    [self.enterBtn setTitle:@"进入主页" forState:UIControlStateNormal];
    [self.enterBtn addTarget:self action:@selector(chooseSchool) forControlEvents:UIControlEventTouchUpInside];
    self.enterBtn.titleLabel.font = [UIFont boldSystemFontOfSize:22*AutoScaleHorizontal];
    [self.enterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:self.enterBtn];
    [self.enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).with.offset(-150*AutoScaleHorizontal);
        make.centerY.mas_equalTo(self.view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 80*AutoScaleVertical));
    }];
    //箭头
    self.enterImage = [[UIImageView alloc]init];
    self.enterImage.image = [UIImage imageNamed:@"chooseSchool"];
    [self.enterBtn addSubview:self.enterImage];
    [self.enterImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.enterBtn.mas_centerY);
        make.right.mas_equalTo(self.enterBtn.mas_right).with.offset(-50*AutoScaleHorizontal);
        make.size.mas_equalTo(CGSizeMake(10*AutoScaleHorizontal, 10*AutoScaleVertical));
    }];
}
#pragma mark 同步数据
#pragma mark 同步数据
-(void)uploadData{
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    //获取全部数据
    NSString* str = [user objectForKey:@"AllData"];
    //    NSLog(@"eee===%@",str);
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    //拿到本地数据
    NSMutableArray * localChildListArray = [_allDataDictionary objectForKey:@"ChildList"];
    NSMutableArray * localClassListArray = [_allDataDictionary objectForKey:@"ClassList"];
    NSMutableArray * localProgramsArray = [_allDataDictionary objectForKey:@"Programs"];
    NSMutableArray * localTestResultArray = [_allDataDictionary objectForKey:@"TestResult"];
    //遍历得到需要上传的数据
    //*****************************agencyid////////////////////////////////////////////////////////////////////
    NSInteger  agencyId = [[user objectForKey:@"AgencyId"]integerValue];
    //agencyid////////////////////////////////////////////////////////////////////
    
    //*****************************删除的对象////////////////////////////////////////////////////////////////////
    NSMutableDictionary * deletedDic = [[NSMutableDictionary alloc]init];
    //已经删除的孩子数组
    NSMutableArray * ChildIdArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteChildArray"] != nil) {
        
        NSString* str = [user objectForKey:@"deleteChildArray"];
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        ChildIdArr = [dict objectForKey:@"deleteChildArray"];
    }
    //已经删除的班级数组
    NSMutableArray * ClassArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteClassArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteClassArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        ClassArr = [dict1 objectForKey:@"deleteClassArray"];
    }
    //已经删除的测试计划数组
    NSMutableArray * PlanArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deletePlanArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deletePlanArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        PlanArr = [dict1 objectForKey:@"deletePlanArray"];
    }
    //已经删除的营销孩子数组
    NSMutableArray * MasterArr = [[NSMutableArray alloc]init];
    if ([user objectForKey:@"deleteMasterArray"] != nil) {
        
        NSString* str1 = [user objectForKey:@"deleteMasterArray"];
        NSData *jsonData1 = [str1 dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dict1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingMutableContainers error:nil];
        MasterArr = [dict1 objectForKey:@"deleteMasterArray"];
    }
    
    //将这四个数组设置成对象
    [deletedDic setObject:PlanArr forKey:@"ProgramIdArr"];
    [deletedDic setObject:MasterArr forKey:@"MasterIdArr"];
    [deletedDic setObject:ChildIdArr forKey:@"ChildIdArr"];
    [deletedDic setObject:ClassArr forKey:@"ClassArr"];
    //删除的对象////////////////////////////////////////////////////////////////////
    
    //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadChildListArray = [[NSMutableArray alloc]init];//childlist
    for (NSMutableDictionary * dict in localChildListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadChildListArray addObject:dict];
        }
    }
    //待上传的孩子childlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadClassListArray = [[NSMutableArray alloc]init];//classlist
    for (NSMutableDictionary * dict in localClassListArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadClassListArray addObject:dict];
        }
    }
    //待上传的班级classlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadProgramsArray = [[NSMutableArray alloc]init];//program
    for (NSMutableDictionary * dict in localProgramsArray) {
        NSInteger dictid =[[dict objectForKey:@"Id"]integerValue];
        if (dictid<0 || [dict objectForKey:@"1900V"] !=nil) {
            [readyToLoadProgramsArray addObject:dict];
        }
    }
    //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
    
    //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
    NSMutableArray * readyToLoadTestResultArray = [[NSMutableArray alloc]init];//masterDetail
    for (NSMutableDictionary * dict in localTestResultArray) {
        NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
        NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        int a = 0;
        //先判断MASTER
        NSInteger dictid =[[masterdic objectForKey:@"Id"]integerValue];
        if (dictid<0 || [masterdic objectForKey:@"1900V"] !=nil) {
            a+=1;
        }else{//master没有更新的话， 判断与之对应的detail
            for (NSMutableDictionary * detailDic in detailArr) {
                NSInteger dictid =[[detailDic objectForKey:@"Id"]integerValue];
                if (dictid<0 || [detailDic objectForKey:@"1900V"] !=nil) {
                    a+=1;
                }
            }
        }
        if (a!=0) {
            [newDICTIONARY setObject:masterdic forKey:@"ResultMaster"];
            [newDICTIONARY setObject:detailArr forKey:@"ResultDetail"];
            [readyToLoadTestResultArray addObject:newDICTIONARY];
        }
    }
    if (readyToLoadTestResultArray.count ==0) {
        //没有任何修改  给空数组和空字典
        NSMutableDictionary * dic1= [[NSMutableDictionary alloc]init];
        NSMutableArray * arr1 = [[NSMutableArray alloc]init];
        NSMutableDictionary * newDICTIONARY = [[NSMutableDictionary alloc]init];
        [newDICTIONARY setObject:dic1 forKey:@"ResultMaster"];
        [newDICTIONARY setObject:arr1 forKey:@"ResultDetail"];
        [readyToLoadTestResultArray addObject:newDICTIONARY];
    }
    //待上传的结果result////////////////////////////////////////////////////////////////////
    
    
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //**********************************************************************************************************************************//
    //开始上传
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        /////////////////////请求
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    self.HUD.mode = MBProgressHUDModeIndeterminate;
        //     self.HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/upload/testresult";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSLog(@"%@",url);
        //        NSString * kuohao = @"[]";
        NSNumber * aId= [NSNumber numberWithInteger:agencyId];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
        //设置参数
        NSData * datachild = [NSJSONSerialization dataWithJSONObject:readyToLoadChildListArray options:0  error:nil];
        NSString * jsStrchild = [[NSString alloc]initWithData:datachild encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrchild1 = [self stringCutN:jsStr];
        
        NSData * dataclass = [NSJSONSerialization dataWithJSONObject:readyToLoadClassListArray options:0  error:nil];
        NSString * jsStrclass = [[NSString alloc]initWithData:dataclass encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrclass1 = [self stringCutN:jsStr];
        
        NSData * datapro = [NSJSONSerialization dataWithJSONObject:readyToLoadProgramsArray options:0  error:nil];
        NSString * jsStrpro = [[NSString alloc]initWithData:datapro encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //            NSString *  jsStrpro1 = [self stringCutN:jsStr];
        
        NSData * dataresult = [NSJSONSerialization dataWithJSONObject:readyToLoadTestResultArray options:0  error:nil];
        NSString * jsStrresult = [[NSString alloc]initWithData:dataresult encoding:NSUTF8StringEncoding];//将所需数据转成JS字符串
        //        NSString *  jsStrresult1 = [self stringCutN:jsStr];
        
        NSData *jsonDataPrama = [NSJSONSerialization dataWithJSONObject:deletedDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStringDic;
        jsonStringDic = [[NSString alloc]initWithData:jsonDataPrama encoding:NSUTF8StringEncoding];
        NSString *  useFulString1 = [self stringCutN:jsonStringDic];
        
        NSDictionary * parama = @{@"ServiceUnitId":aId,@"JsonChildList":jsStrchild,@"JsonClassList":jsStrclass,@"JsonProgramList":jsStrpro,@"JsonTestResult":jsStrresult,@"JsonDeleteObj":useFulString1};
        
        //            NSData * Pramadata = [NSJSONSerialization dataWithJSONObject:parama options:NSJSONWritingPrettyPrinted error:nil];
        //            NSString * pramaDic;
        //            pramaDic = [[NSString alloc]initWithData:Pramadata encoding:NSUTF8StringEncoding];
        //        NSString *  prama1 = [self stringCutN:pramaDic];
        ////
        //
        manager.requestSerializer.timeoutInterval = 30;
        [manager POST:url parameters:parama progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"上传大数据 success");
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSMutableDictionary *relationDict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary * newoldDic =[relationDict objectForKey:@"DeleteIdRelation"];//新旧关系
            
//            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            [user removeObjectForKey:@"deleteChildArray"];
            [user removeObjectForKey:@"deleteClassArray"];
            [user removeObjectForKey:@"deletePlanArray"];
            [user removeObjectForKey:@"deleteMasterArray"];
            /**********************************************************************************************************************************/
            //清除新数据的负数ID 和 1900V 改变字段
            //***************************待上传的孩子childlist////////////////////////////////////////////////////////////////////
            NSMutableArray * childNewOld = [newoldDic objectForKey:@"ChildIdRelation"];
            for (NSMutableDictionary * dict in localChildListArray.reverseObjectEnumerator) {
                if ( [dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * childNewoldDic in childNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[childNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[childNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
            }
            //待上传的孩子childlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的班级classlist////////////////////////////////////////////////////////////////////
            NSMutableArray * classNewOld = [newoldDic objectForKey:@"ClassIdRelation"];
            for (NSMutableDictionary * dict in localClassListArray.reverseObjectEnumerator) {
                if ([dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * classNewoldDic in classNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[classNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[classNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
            }
            //待上传的班级classlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的测试计划programlist////////////////////////////////////////////////////////////////////
            NSMutableArray * programNewOld = [newoldDic objectForKey:@"ProgramIdRelation"];
            for (NSMutableDictionary * dict in localProgramsArray.reverseObjectEnumerator) {
                if ([dict objectForKey:@"1900V"] !=nil) {
                    [dict removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * programNewoldDic in programNewOld) {
                    if ([[dict objectForKey:@"Id"]isEqual:[programNewoldDic objectForKey:@"OldId"]] ) {
                        [dict removeObjectForKey:@"Id"];
                        [dict setObject:[programNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                    
                }
            }
            //待上传的测试计划programlist////////////////////////////////////////////////////////////////////
            
            //***************************待上传的测试结果result////////////////////////////////////////////////////////////////////
            NSMutableArray * masterNewOld = [newoldDic objectForKey:@"MasterIdRelation"];
            NSMutableArray * detailNewOld = [newoldDic objectForKey:@"DetailIdRelation"];
            for (NSMutableDictionary * dict in localTestResultArray.reverseObjectEnumerator) {
                NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
                NSMutableArray * detailArr = [dict objectForKey:@"detailList"];
                //先判断MASTER
                if ([masterdic objectForKey:@"1900V"] !=nil) {
                    [masterdic removeObjectForKey:@"1900V"];
                }
                for (NSMutableDictionary * masterNewoldDic in masterNewOld) {
                    if ([[masterdic objectForKey:@"Id"]isEqual:[masterNewoldDic objectForKey:@"OldId"]] ) {
                        [masterdic removeObjectForKey:@"Id"];
                        [masterdic setObject:[masterNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                    }
                }
                //master没有更新的话， 判断与之对应的detail
                for (NSMutableDictionary * detailDic in detailArr.reverseObjectEnumerator) {
                    if ([detailDic objectForKey:@"1900V"] !=nil) {
                        [detailDic removeObjectForKey:@"1900V"];
                    }
                    for (NSMutableDictionary * detailNewoldDic in detailNewOld) {
                        if ([[detailDic objectForKey:@"Id"]isEqual:[detailNewoldDic objectForKey:@"OldId"]] ) {
                            [detailDic removeObjectForKey:@"Id"];
                            [detailDic setObject:[detailNewoldDic objectForKey:@"NewId"] forKey:@"Id"];
                        }
                    }
                    
                }
                
            }
            //待上传的结果result////////////////////////////////////////////////////////////////////
            /**********************************************************************************************************************************/
            
            //将新孩子的负数ID替换? 营销场景
            if ([user objectForKey:@"finalSaleDic"]!=nil) {
                
                NSString * FS = [user objectForKey:@"finalSaleDic"];
                NSData * jsonData = [FS dataUsingEncoding:NSUTF8StringEncoding];
                NSMutableDictionary * mdic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
                NSMutableArray * masterIdArray = [mdic objectForKey:@"finalSaleDic"];
                NSMutableDictionary * newIDDic = [relationDict objectForKey:@"DeleteIdRelation"];//全部关系
                NSMutableArray * newIdArray = [newIDDic objectForKey:@"MasterIdRelation"];//MASTER关系
                
                //循环遍历 替换负数ID
                for ( NSNumber * oldId in masterIdArray.reverseObjectEnumerator) {
                    for (NSMutableDictionary * dic in newIdArray) {
                        if ([oldId isEqual:[dic objectForKey:@"OldId"]]) {
                            [masterIdArray removeObject:oldId];
                            [masterIdArray addObject:[dic objectForKey:@"NewId"]];
                        }
                    }
                }
                
                [mdic removeObjectForKey:@"finalSaleDic"];
                [mdic setObject:masterIdArray forKey:@"finalSaleDic"];
                
                NSData * dataDic = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:nil];
                NSString * FSS = [[NSString alloc]initWithData:dataDic encoding:NSUTF8StringEncoding];
                //
                
                [user removeObjectForKey:@"finalSaleDic"];
                [user setObject:FSS forKey:@"finalSaleDic"];
                
                [user synchronize];
            }
            [self reloadAllData];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传大数据 error");
            NSError * err = error;
            [self showMessage:@"同步失败，请稍后重试"];
            NSLog(@"登陆因为这个失败了%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];
    }
    
}

#pragma mark
#pragma mark 同步数据
-(void)reloadAllData{
    NSLog(@"开始同步");
    //检测网络
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    self.HUD.mode = MBProgressHUDModeIndeterminate;
        //     self.HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];

        NSString * urls = @"/upload/testresult";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * kuohao =@"[]";
        
        NSString *lll = [user objectForKey:@"AgencyId"];
        NSLog(@"%@",lll);
        if (lll.length <= 0) return;
        NSDictionary *parama = @{@"ServiceUnitId":[user objectForKey:@"AgencyId"],@"ChildList":kuohao,@"ClassList":kuohao,@"ProgramList":kuohao};
        [[HttpRequest sharedInstance] postWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"更新成功");
            
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            //将未分班放在最后
            NSMutableArray * classArray=[NSMutableArray array];
            classArray = [dict objectForKey:@"ClassList"];
            NSDictionary * unClassed = [[NSDictionary alloc]init];
            for (NSDictionary*dic in classArray.reverseObjectEnumerator) {
                if ([[dic objectForKey:@"Name"]isEqualToString:@"未分班"]) {
                    unClassed = dic;
                    [classArray removeObject:dic];
                    
                }
            }
            //        [classArray insertObject:unClassed atIndex:0];
            [classArray addObject:unClassed];
            [dict removeObjectForKey:@"ClassList"];
            [dict setObject:classArray forKey:@"ClassList"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            NSString * allstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            //
            [user removeObjectForKey:@"AllData"];
            [user setObject:allstr forKey:@"AllData"];
            [user synchronize];
            [self showMessage:@"同步成功"];
            
        } failure:^(NSError *error) {
            [self showMessage:@"同步失败，请稍后再试"];
            [self.HUD removeFromSuperview];
            self.HUD = nil;
        }];
        
    }
}
//-(void)reloadData{
//    NSLog(@"开始同步");
//    //检测网络
//    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//    //    AFNetworkReachabilityStatusUnknown          = -1,
//    //    AFNetworkReachabilityStatusNotReachable     = 0,
//    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
//    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
//    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//        [self showMessage:@"当前网络状态不佳，请检验"];
//    }else{
//    //菊花
//    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
//    //    _HUD.mode = MBProgressHUDModeIndeterminate;
//    //     _HUD.opacity = 1;
//    self.HUD.color = [UIColor whiteColor];
//    self.HUD.dimBackground = YES;
//    //设置菊花颜色  只能设置菊花的颜色
//    self.HUD.activityIndicatorColor = [UIColor redColor];
//    [self.view addSubview:self.HUD];
//    [self.HUD showAnimated:YES];
//    NSString * urls = @"/upload/testresult";
//    NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
//    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
//    NSString * kuohao =@"[]";
//    NSDictionary *parama = @{@"ServiceUnitId":[user objectForKey:@"AgencyId"],@"ChildList":kuohao,@"ClassList":kuohao,@"ProgramList":kuohao};
//    [[HttpRequest sharedInstance] postWithURLString:url parameters:parama success:^(id responseObject) {
//        NSLog(@"更新成功");
//        [self showMessage:@"更新成功"];
//        [self.HUD removeFromSuperview];
//        self.HUD = nil;
//        NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
//        NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        //将未分班放在最后
//        NSMutableArray * classArray=[NSMutableArray array];
//        classArray = [dict objectForKey:@"ClassList"];
//        NSDictionary * unClassed = [[NSDictionary alloc]init];
//        for (NSDictionary*dic in classArray.reverseObjectEnumerator) {
//            if ([[dic objectForKey:@"Name"]isEqualToString:@"未分班"]) {
//                unClassed = dic;
//                [classArray removeObject:dic];
//                
//            }
//        }
////        [classArray insertObject:unClassed atIndex:0];
//        [classArray addObject:unClassed];
//        [dict removeObjectForKey:@"ClassList"];
//        [dict setObject:classArray forKey:@"ClassList"];
//        NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
//        self.AllStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
////
//        [user removeObjectForKey:@"AllData"];
//        [user setObject:self.AllStr forKey:@"AllData"];
//        [user synchronize];
//        
//    } failure:^(NSError *error) {
//        UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"更新数据失败，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
//        [alc addAction:act];
//        [self presentViewController:alc animated:YES completion:nil];
//        NSError * err = error;
//        NSLog(@"更新因为这个失败了%@",err.description);
//        [self.HUD removeFromSuperview];
//        self.HUD = nil;
//    }];
//
//}
//}

#pragma mark 进入主页
-(void)chooseSchool{
    NSLog(@"进入主页");
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"AllData"] == nil) {
        [self showMessage:@"请先同步数据"];
    }else{

        MainViewController * cvc = [[MainViewController alloc]init];
        UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:cvc];
        navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
        navi.navigationBar.translucent = NO;
        [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
        [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
        
        [self.navigationController presentViewController:navi animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
